package com.wing.res.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.device.model.entity.DeviceWorkshop;
import com.wing.device.model.response.DeviceModelVO;
import com.wing.device.model.response.DeviceVO;
import com.wing.device.service.DeviceModelService;
import com.wing.device.service.DeviceService;
import com.wing.device.service.DeviceWorkshopService;
import com.wing.dict.model.entity.DictLabel;
import com.wing.dict.service.DictLabelService;
import com.wing.product.service.DynamicService;
import com.wing.production.feign.ProductionClient;
import com.wing.production.workOrder.entity.ProProfession;
import com.wing.res.dao.ResWorkStationDao;
import com.wing.res.model.entity.ResWorkStation;
import com.wing.res.model.request.ResWorkStationUpdateForm;
import com.wing.res.model.response.ResWorkStationSearchVo;
import com.wing.res.service.ResWorkStationService;
import com.wing.user.feign.UserClient;
import com.wing.user.model.request.Role;
import com.wing.web.excel.WorkStationExcelIn;
import com.wing.web.utils.JwtUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 工位-ServiceImpl
 *
 * @version 1.1.0
 * @Author hz
 * @Date 2024-09-19 15:33
 **/
@Service
public class ResWorkStationServiceImpl extends ServiceImpl<ResWorkStationDao, ResWorkStation> implements ResWorkStationService {

    @Resource
    private DynamicService dynamicService;
    @Autowired
    private DeviceWorkshopService deviceWorkshopService;
    @Autowired
    private DictLabelService dictLabelService;
    @Autowired
    private DeviceModelService deviceModelService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ProductionClient productionClient;
    @Autowired
    private UserClient userClient;
    
    
    /**
     * 查询工位信息
     *
     * @param pg
     * @param map
     * @return
     */
    @Override
    public Page<ResWorkStationSearchVo> pageList4app(Page<ResWorkStationSearchVo> pg, Map<String, Object> map) {
        List<ResWorkStationSearchVo> vos = this.baseMapper.pageList4app(pg, map);
        pg.setRecords(vos);
        return pg;
    }

    /**
     * 禁用
     *
     * @param id
     * @return
     */
    @Override
    public int cancellation(String id) {
        ResWorkStation resWorkStation = this.baseMapper.selectById(id);
        if (ObjectUtil.isNotEmpty(resWorkStation)) {
            resWorkStation.setIsDeleted(true);
            resWorkStation.setUpdateTime(LocalDateTime.now());
            resWorkStation.setModifier(JwtUtils.getLoginUserId());
            resWorkStation.setModifierName(JwtUtils.getLoginUsername());
        }
        return baseMapper.updateById(resWorkStation);
    }


    /**
     * 启用
     * @param id
     * @return
     */
    @Override
    public int recover(String id) {
        ResWorkStation resWorkStation = this.baseMapper.selectById(id);
        if (ObjectUtil.isNotEmpty(resWorkStation)) {
            resWorkStation.setIsDeleted(false);
            resWorkStation.setUpdateTime(LocalDateTime.now());
            resWorkStation.setModifier(JwtUtils.getLoginUserId());
            resWorkStation.setModifierName(JwtUtils.getLoginUsername());
        }
        return baseMapper.updateById(resWorkStation);
    }

    /**
     * 修改工位信息
     * @param form
     * @return
     */
    @Override
    public int updateWorkStationBy(ResWorkStationUpdateForm form) {
        Long id = form.getId();
        ResWorkStation resWorkStation = this.baseMapper.selectById(id);
        if (StrUtil.isNotEmpty(form.getCode())){
            QueryWrapper<ResWorkStation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code", form.getCode());
            queryWrapper.eq("is_deleted", false);
            ResWorkStation one = this.getOne(queryWrapper);
            if (ObjectUtil.isNotEmpty(one) && !form.getCode().equals(resWorkStation.getCode())){
                return 99;
            }
        }
        if (ObjectUtil.isNotEmpty(resWorkStation)) {
            BeanUtil.copyProperties(form, resWorkStation);
            resWorkStation.setUpdateTime(LocalDateTime.now());
            resWorkStation.setModifier(JwtUtils.getLoginUserId());
            resWorkStation.setModifierName(JwtUtils.getLoginUsername());
            int i = this.baseMapper.updateById(resWorkStation);
            if (i > 0) {
                return 1;
            }
        }
        return 0;
    }

    /**
     * 添加工位信息
     * @param form
     * @return
     */
    @Override
    public int addWorkStationBy(ResWorkStationUpdateForm form) {
        ResWorkStation resWorkStation = new ResWorkStation();
        //生成工位编号
        String taskNo = UniqueIdGeneratorUtil.generateUniqueId("GW", "yyyyMMdd", 1000, 9999);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String code=dynamicService.getDayNextCode("res_work_station");
        String day=simpleDateFormat.format(new Date());
        BeanUtil.copyProperties(form, resWorkStation);
        resWorkStation.setCreateTime(LocalDateTime.now());
        resWorkStation.setCreator(JwtUtils.getLoginUserId());
        resWorkStation.setCreatorName(JwtUtils.getLoginUsername());
        if (StrUtil.isNotEmpty(form.getCode())){
            resWorkStation.setCode(taskNo);
        }
        resWorkStation.setNo(Integer.parseInt(code));
        resWorkStation.setDay(Integer.parseInt(day));
        resWorkStation.setUpdateTime(LocalDateTime.now());
        int insert = this.baseMapper.insert(resWorkStation);
        if (insert>0){
            return 1;
        }
        return 0;
    }

    @Override
    public void importExcel(List<WorkStationExcelIn> list) {
        int i = 1;
        for (WorkStationExcelIn workStation : list) {
            if (StringUtils.isBlank(workStation.getWorkshopName())) {
                throw new BusinessException(300, "第" + i + "行【所在车间】未输入数据");
            }
            if (StringUtils.isBlank(workStation.getLabelName())) {
                throw new BusinessException(300, "第" + i + "行【工位性质】未输入数据");
            }
            if (StringUtils.isBlank(workStation.getDeviceModelName())) {
                throw new BusinessException(300, "第" + i + "行【设备型号(设备SPU)】未输入数据");
            }
            if (StringUtils.isBlank(workStation.getDeviceName())) {
                throw new BusinessException(300, "第" + i + "行【设备编号(设备SKU)】未输入数据");
            }
            if (StringUtils.isBlank(workStation.getProfessionName())) {
                throw new BusinessException(300, "第" + i + "行【责任工种】未输入数据");
            }
            if (StringUtils.isBlank(workStation.getRoleName())) {
                throw new BusinessException(300, "第" + i + "行【责任岗位】未输入数据");
            }
            if (StringUtils.isBlank(workStation.getRemark())) {
                throw new BusinessException(300, "第" + i + "行【备注】未输入数据");
            }
            ResWorkStationUpdateForm form = new ResWorkStationUpdateForm();
            //车间
            DeviceWorkshop deviceWorkshop = deviceWorkshopService.getBaseMapper()
                .selectOne(new QueryWrapper<DeviceWorkshop>().eq("name", workStation.getWorkshopName()));
            if (ObjectUtil.isNotEmpty(deviceWorkshop)) {
                form.setWorkshopId(deviceWorkshop.getId());
            }
            //工位性质
            DictLabel dictLabel = dictLabelService.getOne
                (new QueryWrapper<DictLabel>().eq("dict_type", "station_nature_name")
                    .eq("label_name", workStation.getLabelName()));
            if (ObjectUtil.isNotEmpty(dictLabel)) {
                form.setNature(Long.parseLong(dictLabel.getLabelValue()));
            }
            //设备型号(设备SPU)
            Map<String, Object> params = new HashMap<>();
            params.put("name", workStation.getDeviceModelName());
            List<DeviceModelVO> deviceModelVOList = deviceModelService.list4app(params);
            if (CollectionUtil.isNotEmpty(deviceModelVOList)) {
                form.setDeviceModelSpuId(deviceModelVOList.get(0).getId());
            }
            //设备编号(设备SKU)
            Map<String, Object> params2 = new HashMap<>();
            params.put("name", workStation.getDeviceName());
            List<DeviceVO> deviceVOList= deviceService.list4app(params2);
            if (CollectionUtil.isNotEmpty(deviceVOList)) {
                form.setDeviceSkuId(deviceVOList.get(0).getId());
            }
            //责任工种
            JsonResult<List<ProProfession>> listJsonResult = productionClient.listProfession(workStation.getProfessionName());
            if (listJsonResult != null && CollectionUtil.isNotEmpty(listJsonResult.getData())) {
                form.setProfessionId(listJsonResult.getData().get(0).getId());
            }
            //责任岗位
            JsonResult<List<Role>> roleData = userClient.listAllRole(workStation.getRoleName());
            if (roleData != null && CollectionUtil.isNotEmpty(roleData.getData())) {
                Role role = roleData.getData().get(0);
                form.setPostId(role.getId());
                form.setPostName(workStation.getRoleName());
                //责任部门
                JsonResult<Role> roleById = userClient.getRoleById(role.getParentId());
                if (roleById != null && ObjectUtil.isNotEmpty(roleById.getData())) {
                    Role role1 = roleById.getData();
                    form.setDepartmentId(role1.getId());
                    form.setDepartmentName(role1.getName());
                }
            }
            //备注
            form.setRemark(workStation.getRemark());
            //工位名称
            form.setName(workStation.getWorkshopName().concat("-").concat(form.getDeviceSkuId().toString()));
            
            int result = addWorkStationBy(form);
            if (result == 0) {
                throw new BusinessException("添加失败");
            }
        }
    }
}
